package com.ego.product.web;

import com.ego.common.constant.ElasticsearchConstant;
import com.ego.common.constant.SystemConstant;
import com.ego.common.util.StringUtil;
import com.ego.common.vo.es.SearchParam;
import com.ego.common.vo.es.SearchResult;
import com.ego.product.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: ego
 * @description: 搜索
 * @author: KamTang
 * @create: 2022-12-02 16:15
 **/
@Controller
public class SearchController {

    @Autowired
    private SearchService searchService;

    @GetMapping({"/search", "/search.html"})
    public String search(SearchParam param, Model model, HttpServletRequest request) throws UnsupportedEncodingException {
        String query = request.getQueryString();
        if (query != null && query.contains(SystemConstant.UNENCRYPTED_SYMBOL) && query.contains(ElasticsearchConstant.ARGUMENTS_ATTRS)) {
            String replace = query.replace(SystemConstant.UNENCRYPTED_SYMBOL, "%2B");
            String decode = URLDecoder.decode(replace, StandardCharsets.UTF_8.name());
            List<String> attrs = StringUtil.getAttrs(decode, ElasticsearchConstant.ARGUMENTS_ATTRS + "=");
            if (attrs.size() != 0) {
                param.setAttrs(attrs);
            }
        }
        param.setQuery(query);
        SearchResult result = searchService.search(param);
        model.addAttribute("result", result);
        return "search";
    }
}
